package band.wukong.practice.mina.quickstart.reverser;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Desc:
 * author: wukonggg@139.com
 */
public class ReverseProtocolHandler extends IoHandlerAdapter {

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        // Close connection when unexpected exception is caught.
        session.close();
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        // Reverse reveiced string
        String str = message.toString();
        StringBuilder buf = new StringBuilder(str.length());
        for (int i = str.length() - 1; i >= 0; i--) {
            buf.append(str.charAt(i));
        }

        // and write it back.
        session.write(buf.toString());
    }


}
